import axios from 'axios';
import router from '@/router'
import Vue from 'vue'
import {
	formatUrlParams
} from './utils.js'
import {
	getToken,
	setToken
} from '@/utils/auth'
import constant from '@/utils/constant'

// 创建axios实例
let service = axios.create({
	// baseURL: constant.baseUrl, // api的base_url
	timeout: 20000 // 请求超时时间
});
// request拦截器
service.interceptors.request.use(config => {
	debugger
	let token = "";
	let flag = "";
	let urlParams = '';
	if (config.method == "get") {
		urlParams = formatUrlParams(config.url);
		if(urlParams && urlParams !=undefined){
			flag = urlParams.flag;
		}
	} else {
		flag =config.data['flag'];
	}

	if (config.url.indexOf('login') == -1) {
		//有一些公共的两边都需要的，则根据flag获取对应系统的token
		if (flag&&flag!=undefined && flag!='') {
			if (flag == "wx") {
				token = localStorage.getItem(constant.WX_TOKEN);
			} else {
				token = localStorage.getItem(constant.YS_TOKEN);
			}
		} else {
			if (config.url.indexOf("wx") >= 0) {
				token = localStorage.getItem(constant.WX_TOKEN);
			} else if (config.url.indexOf("tech") > 0) {
				token = localStorage.getItem(constant.YS_TOKEN);
			} else {
				token = localStorage.getItem(constant.TOKEN);
			}
		}

		config.headers = {
			'Authorization': token, //携带权限参数
			'Cache-Control': 'no-cache', //不使用缓存
			'Pragma': 'no-cache'
		};
	}
	return config;
}, error => {
	Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(response => {
		if (response.config.responseType == 'blob') {
			return response;
		}
		const res = response.data;
		// debugger
		if (res.resultCode !== 0) {
			if (response.config.url.indexOf('login') == -1) {
				Vue.prototype.$toast({
					text: res.resultMsg || res.message || '系统异常' + "!",
					type: 'danger',
					duration: 3000
				});
			}
			debugger
			// 根据服务端约定的状态码：40101:登录失效;
			if (res.resultCode === 40101) {
				localStorage.clear();
				//员工
				if (response.config.url.indexOf('tech') >= 0) {
					window.location.href = constant.loginUrl;
				} else {
					window.location.href = constant.userLoginUrl;
				}
			} else {
				return res;
			}

		} else {
			return response.data;
		}
	},
	error => {
		if (error.url.indexOf('tech') >= 0) {
			window.location.href = constant.loginUrl;
		} else {
			window.location.href = constant.userLoginUrl;
		}
	}
)

export default service;
